/*
 *  Copyright 2010 mazhao.
 * 
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 * 
 *       http://www.apache.org/licenses/LICENSE-2.0
 * 
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 *  under the License.
 */

package shopping.customer;

import com.opensymphony.xwork2.ModelDriven;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Result;
import shopping.commons.BaseAction;
import shopping.commons.Digester;
import shopping.commons.Util;
import shopping.model.LoginInfo;

/**
 * @author mazhao
 */
public class ChangePasswordAction extends BaseAction implements ModelDriven<LoginInfo> {

    /**
     * set user name before change password
     * @return
     */
    @Action(value = "/customer/showchangepwd",
            results = {
                    @Result(name = "success", location = "/WEB-INF/content/customer/change-password.jsp")
    })
    public String showChangePassword() {
        log.debug("enter customer/showchangepwd action");

        LoginInfo login = Util.Security.retriveUserFromSession();
        this.model.setUsername(login.getUsername());

        return SUCCESS;
    }

    /**
     * change user password
     * @return
     */
    @Action(value = "/customer/changepwd",
            results = {
                    @Result(name = "success", location = "showclientcenter", type = "chain")
    })
    public String changePassword() {
        log.debug("enter customer/changepwd action, model:" + model);

        // 1. check password and repassword

        if (!model.getPassword().equals(model.getRePassword())) {
            return INPUT;
        }

        // 2. check old password
        LoginInfo info = new LoginInfo();
        info.setUsername(getModel().getUsername());

        if (!info.load() || !info.getPassword().equals(Digester.crypt(getModel().getPassword()))) {
            // old user not exist or old password not equals
            return INPUT;
        }

        // 3. generate new password hash
        String newpwd = Digester.crypt(model.getPassword());
        info.setPassword(newpwd);

        // 4. update login info
        info.update();

        log.debug("update password successfully!");
        return SUCCESS;
    }

    //=============================================
    // Model Driven interface property and method
    //=============================================
    private LoginInfo model = new LoginInfo();

    public LoginInfo getModel() {
        return model;
    }
}
